import 'dart:io';

import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/common/model/upload_result_entity.dart';
import 'package:tender_flutter/page/supplier/api/api_supplier.dart';
import 'package:tender_flutter/page/supplier/model/certificate_entity.dart';
import 'package:tender_flutter/page/supplier/model/supplier_params_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/utils/utils.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';

class SupplierCertificateListPage extends StatefulWidget {
  /// 供应商基本信息表单参数（页面传值）
  final SupplierParamsEntity paramsEntity;

  const SupplierCertificateListPage({Key key, this.paramsEntity})
      : super(key: key);

  @override
  _SupplierCertificateListPageState createState() =>
      _SupplierCertificateListPageState();
}

class _SupplierCertificateListPageState
    extends State<SupplierCertificateListPage> {
  /// 资质证书数据
  List<CertificateEntity> listDatas = [];

  /// 加入供应商
  Future _joinSupplier() async {
    ToastUtils.showLoading("");

    List<Future> uploadApis = [];

    /// 上传所有资质证书图片
    if (listDatas.isNotEmpty) {
      uploadApis.addAll(listDatas.map((e) => _uploadImage(e.licensePic)
          .then((value) => e.licensePic = value.url)));
    }

    if (!isEmpty(widget.paramsEntity.companyLogo)) {
      /// 上传公司logo
      uploadApis.add(_uploadImage(widget.paramsEntity.companyLogo)
          .then((value) => widget.paramsEntity.companyLogo = value.url));
    }

    if (!isEmpty(widget.paramsEntity.licensePic)) {
      /// 上传公司营业执照
      uploadApis.add(_uploadImage(widget.paramsEntity.licensePic)
          .then((value) => widget.paramsEntity.licensePic = value.url));
    }

    Future.wait(uploadApis).then((value) {
      _submitFormData().then((value) {
        ToastUtils.dismissLoading();
        if (value.status == Status.SUCCESS) {
          // ToastUtils.show("加入成功");
          // LRouter.navigatorCtx(context).popUntilRoot();
          LRouter.navigatorCtx(context).push(Routes.publishSuccessPage);
        }
      });
    }).catchError((e) {
      ToastUtils.dismissLoading();
      ToastUtils.show("图片资源处理失败");
    });
  }

  /// 提交表单数据
  Future<ApiResponse<dynamic>> _submitFormData() async {
    return await ApiSupplier.joinSupplier<dynamic>(
        areaCode: widget.paramsEntity.areaId,
        address: widget.paramsEntity.address,
        companyLogo: widget.paramsEntity.companyLogo,
        companyName: widget.paramsEntity.companyName,
        contact: widget.paramsEntity.contact,
        faRen: widget.paramsEntity.faRen,
        licensePic: widget.paramsEntity.licensePic,
        name: widget.paramsEntity.name,
        phone: widget.paramsEntity.phone,
        remark: widget.paramsEntity.remark,
        title: widget.paramsEntity.title,
        type: widget.paramsEntity.type,
        wxAccount: widget.paramsEntity.wxAccount,
        industryIds: widget.paramsEntity.labels,
        profiles: listDatas.map((e) => e.toJson()).toList());
  }

  /// 上传资质证书
  Future _uploadImage(String path) async {
    if (path.startsWith("http")) {
      var res = UploadResultEntity();
      res.url = path;
      return res;
    }
    ApiResponse<UploadResultEntity> response =
        await ApiCommon.uploadImage([File(path)]);
    return response.result;
  }

  _addCertificate() {
    LRouter.navigatorCtx(context)
        .push(Routes.supplierAddCertificatePage,
            arguments: SupplierAddCertificatePageArguments(
                certificateEntity: CertificateEntity()))
        .then((value) {
      if (value != null) {
        setState(() {
          listDatas.add(value);
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeColors.colorWhite,
        appBar: _initAppBar(),
        body: _initBody());
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("我的资质证书", style: FonStyle.navTextStyle()),
      actions: [
        Container(
          width: ScreenAdapter.width(140),
          height: ScreenAdapter.height(50),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(ScreenAdapter.width(10))),
          alignment: Alignment.center,
          child: FlatButton(
            onPressed: () {
              _addCertificate();
            },
            child: Text(
              "+新增资质",
              maxLines: 1,
              style: TextStyle(
                  fontSize: ScreenAdapter.sp(26),
                  color: ThemeColors.colorType6),
            ),
          ),
        )
      ],
    );
  }

  /// 内容提
  Widget _initBody() {
    return Column(
      children: <Widget>[Expanded(child: _initListView()), _initSubmitBtn()],
    );
  }

  Widget _initListView() {
    if (listDatas.isEmpty) {
      return _emptyView();
    }

    return ListView.separated(
      shrinkWrap: true,
      itemCount: listDatas.isEmpty ? 0 : listDatas.length,
      itemBuilder: (BuildContext context, int index) {
        return _getCertificateItem(index, listDatas[index]);
      },
      separatorBuilder: (BuildContext context, int index) {
        return index > 0
            ? Divider(
                height: ScreenAdapter.height(10),
                color: ThemeColors.colorType11,
              )
            : Divider(
                height: ScreenAdapter.height(10),
                color: ThemeColors.colorWhite,
              );
      },
    );
  }

  /// 提交按钮
  Widget _initSubmitBtn() {
    return Container(
      height: ScreenAdapter.height(90),
      width: double.infinity,
      margin: EdgeInsets.symmetric(
          vertical: ScreenAdapter.height(50),
          horizontal: ScreenAdapter.width(30)),
      decoration: BoxDecoration(
          color: ThemeColors.colorType6,
          borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
      child: FlatButton(
          onPressed: () {
            _joinSupplier();
          },
          child: Text("立即加入",
              style: TextStyle(
                  color: ThemeColors.colorWhite,
                  fontSize: ScreenAdapter.sp(32)))),
    );
  }

  /// 资质Item
  Widget _getCertificateItem(int index, CertificateEntity entity) {
    return Container(
        margin: EdgeInsets.only(
            top: ScreenAdapter.height(35),
            left: ScreenAdapter.width(30),
            right: ScreenAdapter.width(30)),
        padding: EdgeInsets.all(ScreenAdapter.width(30)),
        decoration: BoxDecoration(
            border: new Border.all(width: 1, color: ThemeColors.colorType39),
            borderRadius: BorderRadius.circular(ScreenAdapter.width(10))),
        child: Column(children: <Widget>[
          Container(
              padding: EdgeInsets.only(bottom: ScreenAdapter.width(35)),
              decoration: BoxDecoration(
                border: Border(
                    bottom:
                        BorderSide(width: 1, color: ThemeColors.colorType39)),
              ),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    // Text(entity.title ?? ""),
                    Flexible(
                        fit: FlexFit.loose,
                        child: Text(
                          entity.title ?? "",
                          softWrap: false,
                          overflow: TextOverflow.ellipsis,
                        )),
                    GestureDetector(
                        onTap: () {
                          LRouter.navigatorCtx(context)
                              .push(Routes.supplierAddCertificatePage,
                                  arguments:
                                      SupplierAddCertificatePageArguments(
                                          certificateEntity: entity))
                              .then((value) {
                            if (value != null) {
                              setState(() {
                                entity = value;
                              });
                            }
                          });
                        },
                        child: Text(
                          "编辑",
                        )),
                  ])),
          SizedBox(height: ScreenAdapter.height(20)),
          Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                    width: ScreenAdapter.width(450),
                    // width: double.minPositive,
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text("证书编号：" + entity.code ?? ""),
                          SizedBox(height: ScreenAdapter.height(15)),
                          Text("资质类别：" + entity.regType ?? ""),
                          SizedBox(height: ScreenAdapter.height(15)),
                          Text(
                            "发证日期：" + entity.issueDate ?? "",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(height: ScreenAdapter.height(15)),
                          Text(
                            "截止日期：" + entity.endDate ?? "",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(height: ScreenAdapter.height(15)),
                          Text(
                            "发证机关：" + entity.issueAuthority ?? "",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(height: ScreenAdapter.height(15)),
                        ])),
                Image.file(
                  File(entity.licensePic),
                  fit: BoxFit.cover,
                  width: ScreenAdapter.width(160),
                  height: ScreenAdapter.height(80),
                )
              ])
        ]));
  }

  Widget _emptyView() {
    return Container(
        width: double.infinity,
        height: double.infinity,
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(RPath.imgPath + 'img_empty.png',
                width: ScreenAdapter.width(200),
                height: ScreenAdapter.height(200)),
            SizedBox(height: ScreenAdapter.height(15)),
            GestureDetector(
              child: Container(
                  height: ScreenAdapter.height(90),
                  width: ScreenAdapter.width(600),
                  margin: EdgeInsets.only(top: ScreenAdapter.height(100)),
                  decoration: BoxDecoration(
                      // color: ThemeColors.colorType6,
                      borderRadius:
                          BorderRadius.circular(ScreenAdapter.width(14))),
                  child: FlatButton(
                      onPressed: () {
                        _addCertificate();
                      },
                      child: Text("添加资质",
                          style: TextStyle(
                              color: ThemeColors.colorType50,
                              fontSize: ScreenAdapter.sp(30))))),
            )
          ],
        ));
  }
}
